<?php
declare(strict_types=1);

namespace App\Wxc\Service;

use App\Wxc\Dto\WxcSharerMpToken;
use App\Wxc\Model\WxcSharerMpUser;
use App\Wxc\Service\Input\SendMpMsgInput;
use App\Wxc\Service\Input\SharerMpLoginInput;
use EasyWeChat\MiniApp\Application;
use Exception;
use Hyperf\Config\Annotation\Value;

/**
 * 分享员小程序端服务
 */
class WxcSharerMpService
{
    #[Value('wxc_sharer_mp')]
    protected array $config = [];

    protected Application $miniProgram;


    public function __construct()
    {
        $this->miniProgram = new Application($this->config);
    }

    public function login(SharerMpLoginInput $input)
    {
        //return $this->loginTest($input);

        $s = $this->miniProgram->getUtils()->codeToSession($input->code);
        if (!empty($s['errcode'])) {
            throw new Exception($s['errcode'] . ', ' . $s['errmsg']);
        }

        /** @var WxcSharerMpUser $user */
        $user = WxcSharerMpUser::where('openid', $s['openid'])->first();
        if (!$user) {
            $user = new WxcSharerMpUser();
            $user->openid = $s['openid'];
        }
        $user->session_key = $s['session_key'];
        $user->unionid = $s['unionid'] ?? '';
        $user->save();

        $token = container()->get(WxcSharerMpToken::class)->getToken($user->only(['mp_uid', 'openid']));

        return [
            'openid' => $user->openid,
            'nickname' => $user->nickname,
            'avatar' => $user->avatar,
            'token' => $token
        ];
    }

    public function getUserInfo()
    {
        return container()->get(WxcSharerMpToken::class)->getParserData();
    }

    // 发送订阅消息
    public function sendMessage(SendMpMsgInput $input)
    {
        return $this->miniProgram->getClient()->postJson('/cgi-bin/message/subscribe/send', $input->toArray());
    }
}